<template>
  <ProjectInfo
    :projectId="`${route.query.projectId}`"
    :reportType="'DDGUEF'"
    :sign="true"
    :sync="true"
    :sync-content="'从方案同步数据'"
    @on-sync-header="syncSchemeData"
    :preview=true
    @preview-file="previewFile"
    ref="projectInfoRef"
    :needSignatureCheck="true"
    @signature="handleSignature"
  />
  <!-- Use ContentWrap to wrap the main content -->
  <ContentWrap class="consumable-content-wrap">
    <!-- Header Container for Title and Button -->
    <div class="header-container-consumable">
      <!-- Title Centered -->
      <h2 class="centered-title-consumable">测尘滤膜、吸收液、耗材申请及领用表</h2>
      <!-- Button Right Aligned -->
    </div>

    <el-form
      :inline="true"
      :model="formData"
      class="form-header"
      label-position="left"
      label-width="auto"
    >
      <el-form-item label="检测任务编号">
        <el-input
          v-model="formData.taskNumber"
          placeholder="请输入检测任务编号"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="耗材准备完成日期">
        <el-date-picker
          v-model="formData.completionDate"
          placeholder="选择日期"
          style="width: 200px"
          type="date"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </el-form>

    <!-- Consumable List Table -->
    <el-table :data="formData.consumableList" border stripe style="width: 100%; margin-top: 20px">
      <el-table-column align="center" label="序号" type="index" width="60">
        <template #default="{ $index }">
          <span>{{ $index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="耗材名称" prop="name" width="120">
        <template #default="{ row }">
          <el-input v-model="row.name" placeholder="请输入耗材名称" />
        </template>
      </el-table-column>
      <el-table-column label="检测项目" prop="item">
        <template #default="{ row }">
          <el-input v-model="row.item" placeholder="请输入检测项目" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="申请数量" prop="appliedQuantity" width="120">
        <template #default="{ row }">
          <el-input
            v-model.number="row.appliedQuantity"
            min="0"
            placeholder="数量"
            type="number"
            @input="handleAppliedQuantityChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="领用数量" prop="receivedQuantity" width="120">
        <template #default="{ row }">
          <el-input
            v-model.number="row.receivedQuantity"
            min="0"
            placeholder="数量"
            type="number"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" width="120">
        <template #default="{ row }">
          <el-input v-model="row.remark" placeholder="请输入备注" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150">
        <template #default="{ $index }">
          <el-button link type="primary" @click="addConsumable">添加</el-button>
          <el-button link type="danger" @click="removeConsumable($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  ElButton,
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElTable,
  ElTableColumn
} from 'element-plus'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import { ProjectApi } from '@/api/dk/project'
import ProjectInfo from '@/views/project/list/ProjectInfo.vue'

const router = useRouter()
// 获取路由对象
const route = useRoute()

defineOptions({ name: 'Consumable' })

// 定义耗材项的类型
interface ConsumableItem {
  name: string
  item: string
  appliedQuantity: number | undefined
  receivedQuantity: number | undefined
  remark: string
}

// 表单数据模型
const formData = ref<{
  projectId: string
  taskNumber: string
  completionDate: string
  consumableList: ConsumableItem[]
}>({
  projectId: '',
  taskNumber: '',
  completionDate: '',
  consumableList: []
})

const loading = ref(false)
const projectInfoRef = ref()
// 处理签名事件
const handleSignature = () => {
  // 先进行数据校验
  if (signatureCheck()) {
    // 校验通过，显示签名弹窗
    if (projectInfoRef.value) {
      projectInfoRef.value.showSignatureDialog()
    }
  }
  // 校验不通过时，不显示弹窗，错误信息已在 signatureCheck 中提示
}

// 校验签名前的数据完整性
const signatureCheck = (): boolean => {
  // 校验表格数据不能为空
  if (!formData.value.consumableList || formData.value.consumableList.length === 0) {
    ElMessage.error('至少需要添加一条耗材记录')
    return false
  }

  // 校验每一行的必填字段
  const requiredFields = [
    { key: 'name', label: '耗材名称' },
    { key: 'item', label: '检测项目' },
    { key: 'appliedQuantity', label: '申请数量' },
    { key: 'receivedQuantity', label: '领用数量' }
  ]

  for (let i = 0; i < formData.value.consumableList.length; i++) {
    const row = formData.value.consumableList[i]
    const rowIndex = i + 1

    for (const field of requiredFields) {
      const value = row[field.key as keyof ConsumableItem]

      // 检查值是否为空
      let isEmpty = false
      if (value === undefined || value === null || value === '') {
        isEmpty = true
      } else if (typeof value === 'number' && (isNaN(value) || value <= 0)) {
        // 对于数量字段，检查是否为正数
        isEmpty = true
      }

      if (isEmpty) {
        ElMessage.error(`第${rowIndex}行的"${field.label}"不能为空`)
        return false
      }
    }
  }

  return true
}
/** 添加开始调查方法 */
const previewFile = () => {
  // 跳转到现场调查页面，并携带项目信息
  const { projectId, projectNo } = route.query
  router.push({
    path: '/previewFile',
    query: {
      projectId: projectId,
      projectNo: projectNo,
      operationType: 6
    }
  })
}

// 同步方案数据
const syncSchemeData = async () => {
  try {
    await ElMessageBox.confirm('已有数据将被覆盖，确认是否同步？', '确认同步', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
  } catch (_) {
    return
  }
  loading.value = true

    const projectId = route.query.projectId as string
    const schemeData = await ProjectApi.getDefaultConsumable(Number(projectId))

    // 如果当前列表为空，直接同步数据
    if (formData.value.consumableList.length === 0) {
      formData.value.consumableList = schemeData.map((item) => ({
        name: item.name,
        item: item.item,
        appliedQuantity: item.appliedQuantity,
        receivedQuantity: item.appliedQuantity,
        remark: ''
      }))
      ElMessage.success('同步方案耗材成功')
      return
    }

    // 收集变更信息
    const changes = {
      newItems: [] as string[], // 新增的耗材名称
      updatedItems: [] as string[], // 更新的检测项目
      quantityChanges: [] as string[] // 申请数量的变化
    }

    // 遍历方案数据
    schemeData.forEach((schemeItem) => {
      // 查找是否存在相同name的耗材
      const existingItem = formData.value.consumableList.find(
        (item) => item.name === schemeItem.name
      )

      if (existingItem) {
        // 如果存在，检查item和appliedQuantity的变化
        if (existingItem.item !== schemeItem.item) {
          changes.updatedItems.push(`${schemeItem.name}: ${existingItem.item} → ${schemeItem.item}`)
        }

        if (existingItem.appliedQuantity !== schemeItem.appliedQuantity) {
          const change = schemeItem.appliedQuantity - (existingItem.appliedQuantity || 0)
          const changeText = change > 0 ? '增加' : '减少'
          changes.quantityChanges.push(`${schemeItem.name}: ${changeText} ${Math.abs(change)} 个`)
        }
      } else {
        // 如果不存在，记录新增的耗材
        changes.newItems.push(schemeItem.name)
      }
    })


}

// 初始化数据
onMounted(async () => {
  try {
    // 获取路由参数
    const projectId = route.query.projectId as string
    const projectNo = route.query.projectNo as string

    // 获取已有数据
    const existingData = await ProjectApi.getConsumableInfo(Number(projectId))

    // 判断返回的数据是否为空
    if (!existingData || !existingData.consumableList || existingData.consumableList.length === 0) {
      // 如果数据为空，设置初始值
      formData.value.projectId = projectId
      formData.value.taskNumber = projectNo
      formData.value.completionDate = new Date().toISOString().split('T')[0]
    } else {
      // 如果有数据，直接使用返回的数据
      formData.value = {
        projectId: existingData.projectId,
        taskNumber: existingData.taskNumber,
        completionDate: existingData.completionDate,
        consumableList: existingData.consumableList
      }
    }
  } catch (error) {
    console.error('获取耗材信息失败:', error)
    // 发生错误时设置默认值
    const projectId = route.query.projectId as string
    const projectNo = route.query.projectNo as string
    formData.value.projectId = projectId
    formData.value.taskNumber = projectNo
    formData.value.completionDate = new Date().toISOString().split('T')[0]
  }
})

// 添加耗材行
const addConsumable = () => {
  formData.value.consumableList.push({
    name: '',
    item: '',
    appliedQuantity: undefined,
    receivedQuantity: undefined,
    remark: ''
  })
}

// 监听申请数量变化，自动更新领用数量
const handleAppliedQuantityChange = (row: ConsumableItem) => {
  if (row.appliedQuantity !== undefined) {
    row.receivedQuantity = row.appliedQuantity
  }
}

// 移除耗材行
const removeConsumable = (index: number) => {
  formData.value.consumableList.splice(index, 1)
}

// 保存表单数据
const saveForm = () => {
  // 验证领用数量是否已填写
  const invalidItems = formData.value.consumableList.filter(
    (item) => item.receivedQuantity === undefined || item.receivedQuantity === null
  )

  if (invalidItems.length > 0) {
    ElMessage.warning('请填写所有耗材的领用数量')
    return
  }

  // 准备保存的数据，包含序号
  const saveData = {
    ...formData.value,
    consumableList: formData.value.consumableList.map((item, index) => ({
      ...item,
      index: index + 1 // 添加序号
    }))
  }
  ProjectApi.updateConsumable(saveData)
  // 这里可以调用API保存数据
  console.log('当前表单数据:', JSON.stringify(saveData))
  if (!loading.value) {
    ElMessage.success('保存成功')
  } else {
    ElMessage.success('同步成功')
  }
  loading.value = false
}
watch(
  formData,
  (newVal, oldVal) => {
    console.log('表单数据全部变化:', newVal)
    saveForm()
  },
  { deep: true }
)
</script>

<style lang="scss" scoped>
.consumable-form-container {
  margin: 20px;
}

.header-container-consumable {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e6eb;
}

.centered-title-consumable {
  text-align: center;
  flex-grow: 1;
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: bold;
}

.header-button-container-consumable {
  text-align: right;
  display: flex;
  gap: 10px;
}

.form-header {
  margin-bottom: 20px;
  padding-left: 0 !important;

  .el-form-item {
    margin-right: 40px;
    margin-bottom: 0;

    &:last-child {
      margin-right: 0;
    }

    :deep(.el-form-item__content) {
      margin-left: 0 !important; // Remove default margin on content that pushes it right
    }
  }

  .el-input,
  .el-date-editor {
    :deep(.el-input__wrapper) {
      padding: 0 8px;
      box-shadow: none !important;
      background-color: transparent !important;
      border-radius: 0;
    }

    :deep(.el-input__inner) {
      height: auto;
      line-height: inherit;
    }
  }
}

:deep(.el-table) {
  --el-table-header-bg-color: #f7f8fa;
  --el-table-border-color: #ebeef5;
  margin: 10px 0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

:deep(.el-table__header) {
  font-weight: 600;

  th {
    background-color: var(--el-table-header-bg-color);
    padding: 12px 0;
    height: 50px;
    font-size: 14px;
  }
}

:deep(.el-table__body) {
  td {
    padding: 12px 0;
    height: 56px;
  }
}

:deep(.el-input__wrapper) {
  padding: 0 8px;
  box-shadow: none !important;
  background-color: transparent !important;
}

:deep(.el-input__inner) {
  height: 32px;
  line-height: 32px;
  border: none;
  padding: 0;
}

:deep(.el-input) {
  width: 100%;
  --el-input-border-radius: 0;
}

:deep(.el-date-editor) {
  width: 100%;
}

.button-container {
  margin-top: 20px;
  text-align: center;
}
</style>
